package com.qf.listen;

import com.qf.config.RedisKey;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 陌人不故
 * @Date: 2022/10/25/22:05
 */
@Component
public class ListenEmailMessage {

    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    RedisTemplate redisTemplate;
    @Value("${spring.mail.username}")
    private String from;


    @RabbitListener(queues = "qflive-email-queue")
    public void sendMail(String email){
        StringBuffer code = new StringBuffer();
        for (int i = 0; i < 6; i++) {
            code.append(new Random().nextInt(10));
        }
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setText(code.toString());
        simpleMailMessage.setSubject("千峰在线教育平台注册验证码");
        simpleMailMessage.setFrom(from);
        simpleMailMessage.setTo(email);
        javaMailSender.send(simpleMailMessage);
        //邮件发送完成后。存在redis中，设置60s的过期时间
        redisTemplate.boundValueOps(RedisKey.VALIDATA_KEY + email).set(code.toString(),60, TimeUnit.SECONDS);
    }
}
